package udpTest;


import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.oio.OioEventLoopGroup;
import io.netty.channel.socket.DatagramChannel;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.channel.socket.oio.OioDatagramChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

import java.net.InetSocketAddress;

/**
 * @Author: jia
 * @Descirption:
 * @Date: 2018/5/18 16:58
 * @Modified By:
 */


public class UdpClient {
    private String ip;
    private int port;
    private Channel channel;
    private Bootstrap b = new Bootstrap();
    EventLoopGroup worker = new OioEventLoopGroup();

    public UdpClient(String ip, int port) {
        this.ip = ip;
        this.port = port;
        start();
    }

    public void start() {

        b.group(worker);
        b.channel(OioDatagramChannel.class);
        b.handler(new ChannelInitializer<DatagramChannel>() {
            @Override
            protected void initChannel(DatagramChannel ch) throws Exception {
                ChannelPipeline p = ch.pipeline();
                p.addLast(new StringDecoder());
                p.addLast(new StringEncoder());
                p.addLast(new UdpClientHandler());
            }
        });
    }

    public void bind() {
        try {
            ChannelFuture f = b.bind(new InetSocketAddress(ip, port)).sync();
            Channel channel = f.channel();
            this.channel = channel;
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public void send(Object o) {
        if (channel == null || !channel.isActive()) {
            bind();
        }
        ChannelFuture future = channel.writeAndFlush(o);

    }
}
